package com.landeb.shop.huo.frag;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.landeb.shop.R;
import com.landeb.shop.huo.BannerLoader;
import com.landeb.shop.huo.Json2Act;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.act.GoodDetailActivity;
import com.landeb.shop.huo.act.MainActivity;
import com.landeb.shop.huo.act.SearchActivity;
import com.landeb.shop.huo.act.WelcomeActivity;
import com.landeb.shop.huo.adapter.FragHomeBottomFixedLVAdapter;
import com.landeb.shop.huo.adapter.FragHomeBottomGvAdapter;
import com.landeb.shop.huo.adapter.FragHomeGridViewAdapter;
import com.landeb.shop.huo.bean.BeanFragHome;
import com.landeb.shop.huo.bean.GoodsFragHome;
import com.landeb.shop.huo.bean.ItemFragHomeBottomGridView;
import com.landeb.shop.huo.bean.ItemFragHomeGridView;
import com.landeb.shop.huo.httpRequest.FragHomeRequest;
import com.landeb.shop.huo.view.FixedGridView;
import com.landeb.shop.huo.view.NoScrollListView;
import com.sunfusheng.marqueeview.MarqueeView;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerClickListener;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class HomeFragment extends Fragment implements View.OnClickListener {
    private View view;
    //new instance 方法所需的 参数
    private static final String BASE_URL = "baseUrl";
    private String mBaseUrl;

    private SwipeRefreshLayout mSRL;
    //用于检测滑动到底部
    private ScrollView mScrollView;
    private LinearLayout mLinearLayout;

    private Button mBtnSearch;
    private LinearLayout mBtnScan, mBtnMsg;

    private Banner mBanner;

    private FixedGridView mGridView;

    private MarqueeView mMarqueeView;
    private Button mBtnMore;

    private ImageView mAdView;

    private FixedGridView mBottomGridView;

    private List<String> mBannerUrlList;
    private List<ItemFragHomeGridView> mGridViewItems;//十个按钮的列表
    private List<String> mMarqueeList;
    private List<ItemFragHomeBottomGridView> mBGVItems;

    private FragHomeGridViewAdapter mGVadpter;
    private FragHomeBottomGvAdapter mBGVAdapter;

    private LinearLayout mToRefreshView;
    private LinearLayout mRefreshingView;
    private LinearLayout mFinishedView;

    private SharedPreferences mPreferences;
    private SharedPreferences.Editor mEditor;
    private Gson mGson;
    public static final String HOME_DATA = "homeData";
    public static final String HOME_DATA_DEFAULT = "{\"status\":1,\"info\":\"\\u6210\\u529f\",\"data\":{\"keyword\":\"\\u7c98\\u7389\\u7c73\",\"slider\":[{\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/banner\\/1.jpg\",\"act\":\"url:http:\\/\\/www.baidu.com\"},{\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/banner\\/2.jpg\",\"act\":\"url:http:\\/\\/www.youjie.cm\"},{\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/banner\\/3.jpg\",\"act\":\"url:http:\\/\\/www.lusongsong.com\"},{\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/banner\\/4.jpg\",\"act\":\"url:http:\\/\\/www.net.cn\"}],\"cates\":[{\"name\":\"\\u4eac\\u4e1c\\u8d85\\u5e02\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/1.png\",\"act\":\"url:http:\\/\\/www.baidu.com\"},{\"name\":\"\\u5168\\u7403\\u8d2d\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/2.png\",\"act\":\"url:http:\\/\\/www.youjie.cm\"},{\"name\":\"\\u670d\\u88c5\\u57ce\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/3.png\",\"act\":\"url:http:\\/\\/www.lusongsong.com\"},{\"name\":\"\\u4eac\\u4e1c\\u751f\\u9c9c\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/4.png\",\"act\":\"url:http:\\/\\/www.net.cn\"},{\"name\":\"\\u706b\\u8f66\\u7968\\u673a\\u7968\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/5.png\",\"act\":\"url:http:\\/\\/www.net.cn\"},{\"name\":\"\\u5145\\u503c\\u4e2d\\u5fc3\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/6.png\",\"act\":\"url:http:\\/\\/www.net.cn\"},{\"name\":\"\\u9886\\u4eac\\u8c46\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/7.png\",\"act\":\"url:http:\\/\\/www.net.cn\"},{\"name\":\"\\u9886\\u5238\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/8.png\",\"act\":\"url:http:\\/\\/www.net.cn\"},{\"name\":\"\\u4eac\\u4e1c\\u91d1\\u878d\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/9.png\",\"act\":\"url:http:\\/\\/www.net.cn\"},{\"name\":\"\\u5168\\u90e8\",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/cates\\/10.png\",\"act\":\"url:http:\\/\\/www.net.cn\"}],\"news\":[{\"name\":\"\\u7f8e\\u59867\\u5468\\u5e74\\u6ee1199-100\",\"act\":\"url:http:\\/\\/www.baidu.com\"},{\"name\":\"\\u53cc11\\u81ea\\u8425\\u5546\\u54c1\\u5927\\u4fc3\",\"act\":\"url:http:\\/\\/www.youjie.cm\"},{\"name\":\"\\u5c0f\\u7c73\\u65b0\\u54c1\\u4e0a\\u67b6\\u9886100\\u4f18\\u60e0\\u5238\",\"act\":\"url:http:\\/\\/www.lusongsong.com\"},{\"name\":\"\\u81ea\\u917f\\u7ea2\\u9152\\u6ee1299-200\",\"act\":\"url:http:\\/\\/www.net.cn\"}],\"news_pic\":{\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/ad\\/news_ad.jpg\",\"act\":\"url:http:\\/\\/www.baidu.com\"},\"goods\":[{\"goods_id\":\"1\",\"name\":\"\\u30104\\u65a4\\u3011\\u5929\\u52e4\\u65b0\\u9c9c\\u6709\\u673a\\u751c\\u7cef\\u7389\\u7c73\\u68d2\\u771f\\u7a7a\\u7c98\\u7389\\u7c73\\u5c0f\\u9ecf\\u65e9\\u9910\\u7389\\u7c73\\u975e\\u8f6c\\u57fa\\u56e0 \",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/goods\\/1.jpg\",\"price\":\"12.99\",\"act\":\"url:http:\\/\\/www.baidu.com\"},{\"goods_id\":\"1\",\"name\":\"\\u5317\\u98df\\u5bb6 \\u5373\\u98df\\u9ec4\\u7cef\\u7389\\u7c73\\u519c\\u5bb6\\u65b0\\u9c9c\\u751c\\u5ae9\\u7c98\\u7389\\u7c73\\u68d2\\u771f\\u7a7a\\u5305\\u88c5\\u4ea7\\u5730\\u76f4\\u53d1 \",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/goods\\/2.jpg\",\"price\":\"39.99\",\"act\":\"url:http:\\/\\/www.baidu.com\"},{\"goods_id\":\"1\",\"name\":\"\\u65b0\\u8d27\\u4e1c\\u5317\\u519c\\u5ac2\\u7cef\\u7389\\u7c73\\u68d2200g*10\\u652f\\u5409\\u6797\\u9c9c\\u7389\\u7c73\\u7a57 \",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/goods\\/3.jpg\",\"price\":\"41.80\",\"act\":\"url:http:\\/\\/www.baidu.com\"},{\"goods_id\":\"1\",\"name\":\"\\u4e1c\\u5317\\u7c98\\u82de\\u7c73\\u9ecf\\u7389\\u7c73\\u751c\\u7389\\u7c73\\u5e74\\u8d27\\u9ed1\\u9f99\\u6c5f\\u7279\\u4ea7\\u519c\\u5bb6\\u6709\\u673a\\u51bb\\u7cef\\u7389\\u7c7310\\u68d2\\u5305\\u90ae \",\"pic\":\"http:\\/\\/shop.xuji.cm:8080\\/Public\\/images\\/app_demo\\/goods\\/4.jpg\",\"price\":\"35.00\",\"act\":\"url:http:\\/\\/www.baidu.com\"}]}}";
    //    读取首页所需的测试参数
    private String mTestBaseUrl;

    private Retrofit mRetrofit;
    private FragHomeRequest mFragHomeRequest;
    private BeanFragHome mBeanFragHome;

    private int mPage = 1;
    private boolean onNextPage = false;
    private boolean onRefreshing = false;
    private boolean hasNextPage = true;
    /***
     * 懒加载参数  可见性
     */
    private boolean isLoaded = false;
    private boolean isViewPrepared = false; // 标识fragment视图已经初始化完毕


    private NoScrollListView mBottomListView;
    private FragHomeBottomFixedLVAdapter mFragHomeBottomFixedLVAdapter;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(String baseUrl) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //获取frag数据
        if (getArguments() != null) {
            mBaseUrl = getArguments().getString(BASE_URL);
        }

        //  初始化网络读取组件
        OkHttpClient client = MyApplication.getClient();
        mTestBaseUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mTestBaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mFragHomeRequest = mRetrofit.create(FragHomeRequest.class);

        //初始化首页数据，从SP中读取，若没有首页数据，本地加载
        mGson = new Gson();
        mPreferences = getActivity().getSharedPreferences(HOME_DATA, Context.MODE_PRIVATE);
        mEditor = mPreferences.edit();
        String homeData = mPreferences.getString(HOME_DATA, HOME_DATA_DEFAULT);

//        if (homeData != null) {
        BeanFragHome beanFragHome = mGson.fromJson(homeData, BeanFragHome.class);
        mBeanFragHome = beanFragHome;
//        } else {
//
//            BeanFragHome beanFragHome = mGson.fromJson(HOME_DATA_DEFAULT, BeanFragHome.class);
//            mBeanFragHome = beanFragHome;
//        }

        // 初始化列表
        mBannerUrlList = new ArrayList<>();
        mGridViewItems = new ArrayList<>();
        mMarqueeList = new ArrayList<>();
        mBGVItems = new ArrayList<>();


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_home, container, false);

        /** 绑定视图*/
        initView();

        /**网络第一次获取数据*/
//        getData();

        /** 初始化数据*/
        initData();

        /** 绑定事件*/
        initEvent();

        isViewPrepared = true;
        if (!isLoaded && getUserVisibleHint()) {
            refreshData();
            isLoaded = true;
        }

        return view;
    }


    /**
     * 绑定视图
     */
    private void initView() {

        mSRL = (SwipeRefreshLayout) view.findViewById(R.id.frag_home_swipe);

        mScrollView = (ScrollView) view.findViewById(R.id.frag_home_scrollview);
        mLinearLayout = (LinearLayout) view.findViewById(R.id.frag_home_linearLayout);

        mBtnScan = (LinearLayout) view.findViewById(R.id.frag_home_btn_scan);
        mBtnSearch = (Button) view.findViewById(R.id.frag_home_btn_search);
        mBtnMsg = (LinearLayout) view.findViewById(R.id.frag_home_btn_message);

        mBanner = (Banner) view.findViewById(R.id.frag_home_banner);

        mGridView = (FixedGridView) view.findViewById(R.id.frag_home_GridView);
        // TODO: 2016/10/15 禁止gridView滚动

        mMarqueeView = (MarqueeView) view.findViewById(R.id.frag_home_marqueeView);
        mBtnMore = (Button) view.findViewById(R.id.frag_home_btn_more);

        mAdView = (ImageView) view.findViewById(R.id.frag_home_imgV_ad);

        mBottomGridView = (FixedGridView) view.findViewById(R.id.frag_home_bottomGridView);

        mToRefreshView = (LinearLayout) view.findViewById(R.id.frag_home_bottom_toRefresh_view);
        mRefreshingView = (LinearLayout) view.findViewById(R.id.frag_home_bottom_refreshing_view);
        mFinishedView = (LinearLayout) view.findViewById(R.id.frag_home_bottom_finish_view);

        mBottomListView = (NoScrollListView) view.findViewById(R.id.frag_home_bottomListView);
    }

    /**
     * 数据解析
     */
    private void initData() {

        if (mBeanFragHome == null) {

            mGVadpter = new FragHomeGridViewAdapter(getContext(), mGridViewItems);
            mGridView.setAdapter(mGVadpter);

//            mBGVAdapter = new FragHomeBottomGvAdapter(getContext(), mBGVItems);
//            mBottomGridView.setAdapter(mBGVAdapter);

            mFragHomeBottomFixedLVAdapter = new FragHomeBottomFixedLVAdapter(mBGVItems, getActivity());
            mBottomListView.setAdapter(mFragHomeBottomFixedLVAdapter);
            return;
        }


        //赋值搜索框
        mBtnSearch.setText(mBeanFragHome.getData().getKeyword());

        //baner的图片url列表初始化
        for (int i = 0; i < mBeanFragHome.getData().getSlider().size(); i++) {
            mBannerUrlList.add(mBeanFragHome.getData().getSlider().get(i).getPic());
        }
        //设置图片集合
        mBanner.setImages(mBannerUrlList);

        //十个按钮子布局列表初始化
        for (int i = 0; i < mBeanFragHome.getData().getCates().size(); i++) {
            String picUrl = mBeanFragHome.getData().getCates().get(i).getPic();
            String title = mBeanFragHome.getData().getCates().get(i).getName();
            String targetUrl = mBeanFragHome.getData().getCates().get(i).getAct();

            ItemFragHomeGridView v = new ItemFragHomeGridView(picUrl, title, targetUrl);
            mGridViewItems.add(v);
        }
        mGVadpter = new FragHomeGridViewAdapter(getContext(), mGridViewItems);
        mGridView.setAdapter(mGVadpter);


//mMarquee字符串列表

        for (int i = 0; i < mBeanFragHome.getData().getNews().size(); i++) {
            mMarqueeList.add(mBeanFragHome.getData().getNews().get(i).getName());
        }
        mMarqueeView.startWithList(mMarqueeList);
//        mMarqueeList.add("1. 大家好，我是孙福生。");
//        mMarqueeList.add("2. 欢迎大家关注我哦！");
//        mMarqueeList.add("3. GitHub帐号：sfsheng0322");
//        mMarqueeList.add("4. 新浪微博：孙福生微博");
//        mMarqueeList.add("5. 个人博客：sunfusheng.com");
//        mMarqueeList.add("6. 微信公众号：孙福生");

//      图片广告frag home url
        Glide.with(getContext())
                .load(mBeanFragHome.getData().getNews_pic().getPic())
                .fitCenter()
                .placeholder(R.drawable.load_pic_wide9)
                .error(R.drawable.error_pic_wide9)
                .into(mAdView);

//底部商品列表

        for (int i = 0; i < mBeanFragHome.getData().getGoods().size(); i++) {
            String picUrl = mBeanFragHome.getData().getGoods().get(i).getPic();
            String title = mBeanFragHome.getData().getGoods().get(i).getName();
            String price = mBeanFragHome.getData().getGoods().get(i).getPrice();
            String targetUrl = mBeanFragHome.getData().getGoods().get(i).getAct();
            String id = mBeanFragHome.getData().getGoods().get(i).getGoods_id();
            String saleCount = mBeanFragHome.getData().getGoods().get(i).getCount_sale();
            ItemFragHomeBottomGridView item = new ItemFragHomeBottomGridView(picUrl, title, price, targetUrl, id, saleCount);
            mBGVItems.add(item);
        }
//        mBGVAdapter = new FragHomeBottomGvAdapter(getContext(), mBGVItems);
//        mBottomGridView.setAdapter(mBGVAdapter);


        mFragHomeBottomFixedLVAdapter = new FragHomeBottomFixedLVAdapter(mBGVItems, getActivity());
        mBottomListView.setAdapter(mFragHomeBottomFixedLVAdapter);
    }

    /**
     * 绑定事件
     */
    private void initEvent() {
        //下拉刷新监听
        mSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                refreshData();

            }
        });

//        下拉刷新颜色
        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
//滚动到底部监听
//        mScrollView.setOnTouchListener(new View.OnTouchListener() {
//
//            private int lastY = 0;
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
//                if (event.getAction() == MotionEvent.ACTION_UP) {
//                    lastY = mScrollView.getScrollY();
//                    if (lastY == (mLinearLayout.getHeight() - mScrollView.getHeight())) {
//                        // TODO: 2016/10/17 判断scrollview滑动到底部 给底部gridview添加数据
////                        Toast.makeText(getContext(), "滑动到底部了", Toast.LENGTH_SHORT).show();
//
//                        if (hasNextPage) {
//                            mToRefreshView.setVisibility(View.INVISIBLE);
//                            mRefreshingView.setVisibility(View.VISIBLE);
//                            mFinishedView.setVisibility(View.INVISIBLE);
//                        }
//
//                        addMoreData();
//                    }
//                }
//                return false;
//            }
//        });


        // topBar三个按钮的监听
        mBtnScan.setOnClickListener(this);
        mBtnSearch.setOnClickListener(this);
        mBtnMsg.setOnClickListener(this);

        //设置图片加载器
        mBanner.setImageLoader(new BannerLoader());
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();
        mBanner.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                Json2Act.makeJson2Act(mBeanFragHome.getData().getSlider().get(position - 1).getAct(), getContext());
            }
        });

        //给十个按钮设置adapter 和监听事件
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO: 2016/10/17 设置frag home十个按钮的点击事件
//                Toast.makeText(getContext(), mGridViewItems.get(position).getPicUrl() + "", Toast.LENGTH_SHORT).show();
//                Toast.makeText(getContext(), position + "", Toast.LENGTH_SHORT).show();

                String json = mGridViewItems.get(position).getTargetUrl();

                Json2Act.makeJson2Act(json, getContext());

            }
        });
//        取消默认点击效果
//        mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));

        //mMarqueeView装载字符串 并设置监听事件
//        String notice = "心中有阳光，脚底有力量！心中有阳光，脚底有力量！心中有阳光，脚底有力量！";
//        mMarqueeView.startWithText(notice);

        mMarqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                // TODO: 2016/10/17 设置frag home跑马灯点击事件
//                Toast.makeText(getContext(), mMarqueeList.size() + "", Toast.LENGTH_SHORT).show();

                Json2Act.makeJson2Act(mBeanFragHome.getData().getNews().get(position).getAct(), getContext());

            }
        });
        //marquee旁边更多按钮的监听
        mBtnMore.setOnClickListener(this);

        //  图片广告  设置监听
        mAdView.setOnClickListener(this);

//        mBottomGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
//        mBottomGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                // TODO: 2016/10/18 设置底部商品gridView的点击事件
////                Toast.makeText(getContext(), position + "", Toast.LENGTH_SHORT).show();
//                String ID = mBGVItems.get(position).getId();
//                String title = mBGVItems.get(position).getTitle();
//                String price = mBGVItems.get(position).getPrice();
//
//                GoodDetailActivity.toAct(getActivity(), ID, title, price);
//
//
//            }
//        });

        mBottomListView.setSelector(new ColorDrawable(Color.TRANSPARENT));

        mBottomListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String json = mBGVItems.get(position).getMtagetUrl();
                Log.e("bottomACT: ", json);
                Json2Act.makeJson2Act(json, getContext());

            }
        });

    }

    /**
     * 读取下一组产品
     */
    private void addMoreData() {


        if (!onNextPage && hasNextPage) {

            onNextPage = true;
            mPage++;
            mFragHomeRequest.getMoreGoods(mPage)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<GoodsFragHome>() {
                        @Override
                        public void onCompleted() {

                            onNextPage = false;
                            Log.e("addData" + "----page----" + mPage, "successed");

                        }

                        @Override
                        public void onError(Throwable e) {

                            onNextPage = false;


                            mToRefreshView.setVisibility(View.VISIBLE);
                            mRefreshingView.setVisibility(View.INVISIBLE);
                            mFinishedView.setVisibility(View.INVISIBLE);

                            Log.e("addData" + "----page----" + mPage + "+++++++++++++++", "onError");
                        }

                        @Override
                        public void onNext(GoodsFragHome goodsFragHome) {

                            if (goodsFragHome.getStatus() == 1) {

                                hasNextPage = true;

                                mToRefreshView.setVisibility(View.VISIBLE);
                                mRefreshingView.setVisibility(View.INVISIBLE);
                                mFinishedView.setVisibility(View.INVISIBLE);
                            } else {

                                hasNextPage = false;

                                mToRefreshView.setVisibility(View.INVISIBLE);
                                mRefreshingView.setVisibility(View.INVISIBLE);
                                mFinishedView.setVisibility(View.VISIBLE);
                                return;
                            }


                            List<ItemFragHomeBottomGridView> moreList = new ArrayList();

                            for (int i = 0; i < goodsFragHome.getData().size(); i++) {
                                String picUrl = goodsFragHome.getData().get(i).getPic();
                                String title = goodsFragHome.getData().get(i).getName();
                                String price = goodsFragHome.getData().get(i).getPrice();
                                String targetUrl = goodsFragHome.getData().get(i).getAct();
                                String id = goodsFragHome.getData().get(i).getGoods_id();
                                String saleCount = goodsFragHome.getData().get(i).getCount_sale();
                                ItemFragHomeBottomGridView item = new ItemFragHomeBottomGridView(picUrl, title, price, targetUrl, id, saleCount);
                                moreList.add(item);
                            }
                            mBGVItems.addAll(moreList);
                            mBGVAdapter.notifyDataSetChanged();
//
// Toast.makeText(getContext(), goodsFragHome.getResult().size()+"", Toast.LENGTH_SHORT).show();

//                            更新底部
                        }
                    });
        }


    }

    /**
     * 刷新视图
     */
    private void refreshData() {

        mPage = 1;/**刷新后 清空计数器*/
        hasNextPage = true;

        mToRefreshView.setVisibility(View.VISIBLE);
        mRefreshingView.setVisibility(View.INVISIBLE);
        mFinishedView.setVisibility(View.INVISIBLE);

        if (!onRefreshing) {

            onRefreshing = true;

            mFragHomeRequest.getFragHomeIndex()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanFragHome>() {
                                   @Override
                                   public void onCompleted() {
                                       onRefreshing = false;
                                       mSRL.setRefreshing(false);
                                       Log.e("refreshData", "successed");
                                   }

                                   @Override
                                   public void onError(Throwable e) {

                                       onRefreshing = false;
                                       mSRL.setRefreshing(false);
                                       Log.e("refreshData", "onError" + e.toString());

                                   }

                                   @Override
                                   public void onNext(BeanFragHome beanFragHome) {
                                       mBeanFragHome = beanFragHome;
                                       //判断所获取首页数据若正常（success==1），则写入SP下次登录使用
                                       if (beanFragHome.getStatus() == 1) {
                                           String respo = mGson.toJson(beanFragHome);
                                           mEditor.putString(HOME_DATA, respo);
                                           mEditor.apply();
                                       }

                                       //赋值搜索框
                                       mBtnSearch.setText(mBeanFragHome.getData().getKeyword());

                                       // TODO: 2016/10/18 banner未刷新
//                                   //baner的图片url列表更新
//                                   mBanner.stopAutoPlay();
                                       mBannerUrlList.clear();
                                       for (int i = 0; i < mBeanFragHome.getData().getSlider().size(); i++) {
                                           mBannerUrlList.add(mBeanFragHome.getData().getSlider().get(i).getPic());
                                       }
                                       //设置图片集合
                                       mBanner.setImages(mBannerUrlList);
                                       //banner设置方法全部调用完毕时最后调用
                                       mBanner.start().startAutoPlay();

                                       //十个按钮子布局列表初始化
                                       mGridViewItems.clear();
                                       for (int i = 0; i < mBeanFragHome.getData().getCates().size(); i++) {

                                           String picUrl = mBeanFragHome.getData().getCates().get(i).getPic();
                                           String title = mBeanFragHome.getData().getCates().get(i).getName();
                                           String targetUrl = mBeanFragHome.getData().getCates().get(i).getAct();

                                           ItemFragHomeGridView v = new ItemFragHomeGridView(picUrl, title, targetUrl);
                                           mGridViewItems.add(v);
                                       }
                                       mGVadpter.notifyDataSetChanged();

// TODO: 2016/10/18 marquee未刷新
//                                   //mMarquee字符串列表
//mMarquee字符串列表
                                       mMarqueeList.clear();
                                       for (int i = 0; i < mBeanFragHome.getData().getNews().size(); i++) {
                                           mMarqueeList.add(mBeanFragHome.getData().getNews().get(i).getName());
                                       }
                                       mMarqueeView.startWithList(mMarqueeList);


                                       // 图片广告frag home url


                                       Glide.with(getContext())
                                               .load(mBeanFragHome.getData().getNews_pic().getPic())
                                               .fitCenter()
                                               .placeholder(R.drawable.load_pic_wide9)
                                               .error(R.drawable.error_pic_wide9)
                                               .into(mAdView);

                                       //底部商品列表
                                       mBGVItems.clear();
                                       for (int i = 0; i < mBeanFragHome.getData().getGoods().size(); i++) {
                                           String picUrl = mBeanFragHome.getData().getGoods().get(i).getPic();
                                           String title = mBeanFragHome.getData().getGoods().get(i).getName();
                                           String price = mBeanFragHome.getData().getGoods().get(i).getPrice();
                                           String targetUrl = mBeanFragHome.getData().getGoods().get(i).getAct();
                                           String id = mBeanFragHome.getData().getGoods().get(i).getGoods_id();
                                           String saleCount = mBeanFragHome.getData().getGoods().get(i).getCount_sale();
                                           ItemFragHomeBottomGridView item = new ItemFragHomeBottomGridView(picUrl, title, price, targetUrl, id, saleCount);
                                           mBGVItems.add(item);
                                       }
//                                       mBGVAdapter.notifyDataSetChanged();

                                       mFragHomeBottomFixedLVAdapter.notifyDataSetChanged();
                                   }
                               }
                    );
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.frag_home_btn_scan:
                // TODO: 2016/10/17 frag home扫一扫按钮

                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                getActivity().startActivityForResult(intent, MainActivity.ZXING_REQUEST);

                break;
            case R.id.frag_home_btn_search:
                // TODO: 2016/10/17  frag home搜索按钮
                SearchActivity.toAct(getContext());

                break;
            case R.id.frag_home_btn_message:
                // TODO: 2016/10/17  frag home消息按钮
                WelcomeActivity.toAct(getActivity());
                break;
            case R.id.frag_home_btn_more:
                // TODO: 2016/10/17 frag home marquee旁边的按钮
                Toast.makeText(getContext(), v.getId() + "", Toast.LENGTH_SHORT).show();
                break;

            case R.id.frag_home_imgV_ad:
                // TODO: 2016/10/17 frag home adView图片广告监听

                String adJson = mBeanFragHome.getData().getNews_pic().getAct();

                Json2Act.makeJson2Act(adJson, getContext());


                break;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {

            if (isViewPrepared && !isLoaded) {
                refreshData();
                isLoaded = true;
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        isViewPrepared = false;
        isLoaded = false;

    }
}